package org.example.untils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@ServerEndpoint(value = "/chat/{from}")
@Component
public class WebSocketServer {

    private static Logger L = LoggerFactory.getLogger(WebSocketServer.class);

    private static List<SessionWrap> sessionList = new ArrayList<>();

    private Integer from;

    @OnOpen//打开连接
    public void onOpen(Session session, @PathParam("from") Integer from){
        //System.out.println("id："+from+"连接成功");
        this.from=from;
        for (SessionWrap item : sessionList) {
            if(item.getFrom().equals(from)){
                item.setSession(session);
                return;
            }
        }
        SessionWrap sessionWrap=new SessionWrap();
        sessionWrap.setFrom(from);
        sessionWrap.setSession(session);
        sessionList.add(sessionWrap);
    }

    @OnClose//关闭连接
    public void onClose(){
        //System.out.println("id："+from+"断开了连接");
        List<SessionWrap> newSessionList = new ArrayList<>();
        for (SessionWrap item : sessionList) {
            if(item.getFrom().equals(from)){
                continue;
            }
            newSessionList.add(item);
        }
        sessionList=newSessionList;
    }

    @OnMessage//发送消息
    public void onMessage(String message,Session session) throws IOException {
        if (message.equals("心跳测试")){
            //System.out.println("心跳测试");
            return;
        }
        String[] strings=message.split("&");
        Integer to = Integer.valueOf(strings[0]);
        for (SessionWrap item : sessionList) {
            if(item.getFrom().equals(to)){
                item.getSession().getBasicRemote().sendText(strings[1]+"&"+strings[2]+"&"+strings[3]);
                break;
            }
        }
        //System.out.println("id："+from+"消息转发成功。");
        //System.out.println("接收方id："+to);
        //System.out.println("消息："+strings[3]);
    }
}
